package cn.edu.sgu.www.mhxysy.util;

import cn.edu.sgu.www.mhxysy.consts.MimeTypes;
import cn.edu.sgu.www.mhxysy.exception.GlobalException;
import cn.edu.sgu.www.mhxysy.restful.JsonResult;
import cn.edu.sgu.www.mhxysy.restful.ResponseCode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * http工具类
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Slf4j
public class HttpUtils {

    /**
     * 获取HttpServletRequest对象
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

        if (attributes != null ) {
            return ((ServletRequestAttributes) attributes).getRequest();
        }

        throw new GlobalException(ResponseCode.BAD_REQUEST, "获取request对象失败");
    }

    /**
     * 获取HttpServletResponse对象
     * @return HttpServletResponse
     */
    public static HttpServletResponse getResponse() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

        if (attributes != null ) {
            return ((ServletRequestAttributes) attributes).getResponse();
        }

        throw new GlobalException(ResponseCode.BAD_REQUEST, "获取response对象失败");
    }

    /**
     * 获取请求URL地址
     * @return String
     */
    public static String getRequestURI() {
        return getRequest().getRequestURI();
    }

    /**
     * 处理数据导出失败
     * @param response HttpServletResponse对象
     */
    public static void exportFail(HttpServletResponse response) {
        response.reset();

        response.setStatus(ResponseCode.SERVER_ERROR.getValue());
        response.setContentType(MimeTypes.APPLICATION_JSON_CHARSET_UTF_8);

        JsonResult<Void> jsonResult = JsonResult.error("数据导出异常");

        log.error(jsonResult.getMessage());

        try (PrintWriter writer = response.getWriter()){
            writer.write(JSON.toJSONString(jsonResult));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}